// ignore_for_file: non_constant_identifier_names

import 'dart:async';
import 'dart:convert';
import 'package:http_parser/http_parser.dart';
import 'package:sj001/model/conversatinoMessageModel.dart';
import 'package:sj001/model/historyConversionsModel.dart';
import 'package:sj001/model/inputMessage.dart';
import 'package:sj001/model/sendMsgModel.dart';
import 'package:sj001/utils/Utils.dart';
import 'package:http/http.dart' as http;
import '../model/revMsgModel.dart';
import '../sse/constants/sse_request_type_enum.dart';
import '../sse/flutter_client_sse.dart';

class CustomRequest {
  static sendMessageStreaming({
    required String conversation_id,
    required InputMessageModel model,
    Function(RevMsgModel)? onData,
    Function(RevMsgModel)? onDataError,
    Function(String)? onError,
    Function(RevMsgModel)? onDone,
  }) {
    SendMsgModel msg = SendMsgModel(
      inputs: {},
      query: model.content,
      response_mode: 'streaming',
      conversation_id: conversation_id,
      user: Utils.app_user,
      files: [],
    );

    String url = '${Utils.base_url}/${Utils.chat_messages}';
    Map<String, dynamic> body = msg.toJson();
    print('url:$url  ,body:$body');
    SSEClient.subscribeToSSE(
      method: SSERequestType.POST,
      url: url,
      header: {
        'Authorization': 'Bearer ${Utils.app_key}',
        'Content-Type': 'application/json',
        "Accept": "text/event-stream",
        "Cache-Control": "no-cache",
      },
      body: body,
      onData: onData,
      onDone: onDone,
      onError: onError,
      onDataError: onDataError,
    );
  }

  static Future<void> uploadFile({required String filePath}) async {
    // 转换文件为multipart类型
    String url = '${Utils.base_url}/${Utils.uploadFile}';

    var request = http.MultipartRequest("POST", Uri.parse(url));

    // 添加文件
    var multipartFile = await http.MultipartFile.fromPath(
      'file',
      filePath,
      contentType: MediaType('image', '[png|jpeg|jpg|webp|gif]'),
    );
    request.files.add(multipartFile);
    request.fields['user'] = Utils.app_user;
    request.headers['Content-Type'] = 'multipart/form-data';
    request.headers['Authorization'] = 'Bearer ${Utils.app_key}';

    // 发送请求
    try {
      var response = await request.send();
      String rspStr = await response.stream.bytesToString();
      print(rspStr);
    } catch (e) {
      print(e.toString());
    }
  }

  static Future<HistoryConversionsModel?> historyConversations({
    required String lastId,
    int limit = 20,
  }) async {
    String url =
        '${Utils.base_url}/${Utils.historyConversations}?user=${Utils.app_user}&last_id=$lastId&limit=$limit';
    print(url);
    Uri uri = Uri.parse(url);

    var request = http.Request("GET", uri);

    request.headers['Content-Type'] = 'application/json';
    request.headers['Authorization'] = 'Bearer ${Utils.app_key}';

    // 发送请求
    try {
      var response = await request.send();
      String rspStr = await response.stream.bytesToString();
      print(rspStr);
      HistoryConversionsModel model =
          HistoryConversionsModel.fromJson(jsonDecode(rspStr));

      return model;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  static Future<ConversationMessageModel?> conversationsMessages({
    required String conversation_id,
    required String first_id,
    int limit = 20,
  }) async {
    String url =
        '${Utils.base_url}/${Utils.messages}?conversation_id=$conversation_id&user=${Utils.app_user}&first_id=$first_id&limit=$limit';
    print(url);
    Uri uri = Uri.parse(url);
    var request = http.Request("GET", uri);
    request.headers['Content-Type'] = 'application/json';
    request.headers['Authorization'] = 'Bearer ${Utils.app_key}';

    // 发送请求
    try {
      var response = await request.send();
      String rspStr = await response.stream.bytesToString();
      print(rspStr);
      print(rspStr.runtimeType.toString());
      ConversationMessageModel model =
          ConversationMessageModel.fromJson(jsonDecode(rspStr));

      return model;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }



  static Future<ConversationMessageModel?> nextSuggest({required String message_id}) async {
    String url =
        '${Utils.base_url}/${Utils.messages}/$message_id/${Utils.suggested}?user=${Utils.app_user}';
    print(url);
    Uri uri = Uri.parse(url);
    var request = http.Request("GET", uri);
    request.headers['Content-Type'] = 'application/json';
    request.headers['Authorization'] = 'Bearer ${Utils.app_key}';

    // 发送请求
    try {
      var response = await request.send();
      String rspStr = await response.stream.bytesToString();
      print(rspStr);
      ConversationMessageModel model =
      ConversationMessageModel.fromJson(jsonDecode(rspStr));

      return model;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }


  static Future<bool> messageLike({
    required String message_id,
    required rating,
  }) async {
    String url =
        '${Utils.base_url}/${Utils.messages}/$message_id/${Utils.feedbacks}?user=${Utils.app_user}';
    print(url);
    Uri uri = Uri.parse(url);
    var request = http.Request("POST", uri);
    request.headers['Content-Type'] = 'application/json';
    request.headers['Authorization'] = 'Bearer ${Utils.app_key}';
    request.body = jsonEncode({
      'rating':rating,
      'user':Utils.app_user,
    });
    // 发送请求
    try {
      var response = await request.send();
      String rspStr = await response.stream.bytesToString();
      print(rspStr);
      Map<String,dynamic> ret = jsonDecode(rspStr);


      return ret['result'] == 'success';
    } catch (e) {
      print(e.toString());
      return false;
    }
  }


  static Future<ConversationMessageModel?> cancelTask({
    required String task_id,
  }) async {
    String url =
        '${Utils.base_url}/${Utils.chat_messages}/$task_id/stop';
    print(url);
    Uri uri = Uri.parse(url);
    var request = http.Request("POST", uri);
    request.headers['Content-Type'] = 'application/json';
    request.headers['Authorization'] = 'Bearer ${Utils.app_key}';
    request.body = jsonEncode({
      'user':Utils.app_user,
    });
    // 发送请求
    try {
      var response = await request.send();
      String rspStr = await response.stream.bytesToString();
      print(rspStr);
      ConversationMessageModel model =
      ConversationMessageModel.fromJson(jsonDecode(rspStr));

      return model;
    } catch (e) {
      print(e.toString());
      return null;
    }
  }

  static Future<bool> deleteConversion({
    required String conversation_id,
  }) async {
    String url =
        '${Utils.base_url}/${Utils.historyConversations}/$conversation_id';
    print(url);
    Uri uri = Uri.parse(url);
    var request = http.Request("DELETE", uri);
    request.headers['Content-Type'] = 'application/json';
    request.headers['Authorization'] = 'Bearer ${Utils.app_key}';
    request.body = jsonEncode({
      'user':Utils.app_user,
    });
    // 发送请求
    try {
      var response = await request.send();
      String rspStr = await response.stream.bytesToString();
      print(rspStr);
      Map<String,dynamic> ret = jsonDecode(rspStr);
      return ret['status'] == null;
    } catch (e) {
      print(e.toString());
      return false;
    }
  }

}
